const mysql = require("mysql");
const dbConfig = require("./dbConfig");
const sqlMap = require("./sqlMap");
const log = require("./log");
const { query } = require("express");
const Busboy = require('busboy')
const path = require('path')
const fs = require('fs')
const pool = mysql.createPool({
  host: dbConfig.mysql.host,
  user: dbConfig.mysql.user,
  password: dbConfig.mysql.password,
  database: dbConfig.mysql.database,
  port: dbConfig.mysql.port,
  multipleStatements: true, // 多语句查询
});
/**
 * code : 0 -> sql查询失败;msg -> 错误提示
 *        1 -> 查询成功;data -> 返回数据
 *        2 -> 其他错误;msg -> 错误提示
 */
function queryResult(err, result, res) {
  console.log("--------");
  if (err) {
    res.json({ code: 0, msg: "获取数据失败" });
    log.writeLog(err, "err");
  } else {
    res.json({ code: 1, data: result });
  }
}
module.exports = {
  //上传
  uploadFile(req, res, next){
    let busboy =  Busboy({ headers: req.headers });
    let saveTo="";
  busboy.on('file', (fieldname, file, filename, encoding, mimetype) => {
    console.log(filename,"filename")
     saveTo = path.join(__dirname, '/uploads', filename.filename);
    file.pipe(fs.createWriteStream(saveTo));
  });

  busboy.on('finish', function () {
    res.json({ code: 1, data: {url: saveTo} })
  });

  return req.pipe(busboy);
  },
  //获取tel列表
  getTels(req, res, next){
    let postData = req.query;
    pool.getConnection((err, connection) => {
      connection.query(sqlMap.article.getTels,[], (err, result) => {
        // log.writeLog(
        //   "sql:" + sqlMap.article.getTels + ";params:" + ";",
        //   "sql"
        // );
        console.log(sqlMap.article.getTels,"---")
        console.log(result,"222")
        if (err) {
          console.log(err,"err");
          res.json({ code: 0, msg: "获取数据失败" });
          log.writeLog("<getBlogs>" + err, "err");
        } else {
          res.json({ code: 1, data: result });
        }

        
        connection.release();
      });
    });
  },
  //获取connect列表
  getBlogs(req, res, next) {
    let postData = req.query;
    
    pool.getConnection((err, connection) => {
      let sql;
      if(postData.isSearch){
         sql=sqlMap.article.getBlogsByKey
         postData.type=postData.description
         postData.title=postData.description
      }else{
        sql=sqlMap.article.getBlogs
      }
      //console.log(postData,"postData")
      connection.query(sql,[postData.type,postData.description,postData.title], (err, result) => {
        if (err) {
          console.log(err,"err");
          res.json({ code: 0, msg: "获取数据失败" });
          log.writeLog("<getBlogs>" + err, "err");
        } else {
          res.json({ code: 1, data: result });
        }

        log.writeLog(
          "sql:" + sqlMap.article.getBlogs + ";params:" + ";",
          "sql"
        );
        connection.release();
      });
    });
  },
  //获取connect详情
  getBlogDetail(req, res, next) {
    let postData = req.query;
    pool.getConnection((err, connection) => {
      connection.query(
        sqlMap.article.getBlogDetail,
        [postData.id],
        (err, result) => {
          if (err) {
            res.json({ code: 0, msg: "获取数据失败" });
            log.writeLog("<getBlogDetail>" + err, "err");
          } else {
            res.json({ code: 1, data: result });
          }

          log.writeLog(
            "sql:" +
              sqlMap.article.getBlogDetail +
              ";params:" +
              postData.id +
              ";",
            "sql"
          );
          connection.release();
        }
      );
    });
  },
  //登录connect
  login(req, res, next) {
    let postData = req.query;
    pool.getConnection((err, connection) => {
      connection.query(
        sqlMap.other.login,
        [postData.username, postData.password],
        (err, results) => {
          if (err) {
            res.json({ code: 0, msg: "获取数据失败" });
            log.writeLog("<login>" + err, "err");
          } else {
            if (results[0].count == 0) res.json({ code: 2, msg: "密码错误" });
            else if (results[0].count == 1)
              res.json({ code: 1, data: "登录成功" });
          }

          log.writeLog(
            "sql:" +
              sqlMap.other.login +
              ";params:" +
              postData.username +
              "," +
              postData.password +
              ";",
            "sql"
          );
          connection.release();
        }
      );
    });
  },
  //浏览connect
  visit(req, res, next) {
    let postData = req.body;
    pool.getConnection((err, connection) => {
      connection.query(sqlMap.other.visit, [postData], (err, results) => {
        if (err) {
          res.json({ code: 0, msg: "添加失败" });
          log.writeLog("<visit>" + err, "err");
        } else {
          res.json({ code: 1, data: "已添加" });
        }

        log.writeLog(
          "sql:" +
            sqlMap.other.visit +
            ";params:" +
            JSON.stringify(postData) +
            ";",
          "sql"
        );
        connection.release();
      });
    });
  },
  //获取标签
  getTag(req, res, next) {
    let postData = req.query;
    pool.getConnection((err, connection) => {
      connection.query(sqlMap.tag.getTag, (err, result) => {
        if (err) {
          res.json({ code: 0, msg: "获取数据失败" });
          log.writeLog("<getTag>" + err, "err");
        } else {
          res.json({ code: 1, data: result });
        }

        log.writeLog("sql:" + sqlMap.tag.getTag + ";params:" + ";", "sql");
        connection.release();
      });
    });
  },
  //添加类型
  addType(req, res, next) {
    let postData = req.body;
    pool.getConnection((err, connection) => {
      connection.query(sqlMap.type.addType, [postData], (err, result) => {
        if (err) {
          res.json({ code: 0, msg: "添加失败" });
          log.writeLog("<addType>" + err, "err");
        } else {
          res.json({ code: 1, data: "成功添加" });
        }
        log.writeLog(
          "sql:" +
            sqlMap.type.addType +
            ";params:" +
            JSON.stringify(postData) +
            ";",
          "sql"
        );
        connection.release();
      });
    });
  },
  //添加标签
  addTag(req, res, next) {
    let postData = req.body;
    pool.getConnection((err, connection) => {
      connection.query(sqlMap.tag.addTag, [postData], (err, result) => {
        if (err) {
          res.json({ code: 0, msg: "添加失败" });
          log.writeLog("<addTag>" + err, "err");
        } else {
          res.json({ code: 1, data: "成功添加" });
        }

        log.writeLog(
          "sql:" +
            sqlMap.tag.addTag +
            ";params:" +
            JSON.stringify(postData) +
            ";",
          "sql"
        );
        connection.release();
      });
    });
  },
  //删除
  deleteTag(req, res, next) {
    let postData = req.body;
    pool.getConnection((err, connection) => {
      connection.query(sqlMap.tag.deleteTag, [postData.id], (err, result) => {
        if (err) {
          res.json({ code: 0, msg: "删除失败" });
          log.writeLog("<deleteTag>" + err, "err");
        } else {
          res.json({ code: 1, data: "成功删除" });
        }

        log.writeLog(
          "sql:" + sqlMap.tag.deleteTag + ";params:" + postData.id + ";",
          "sql"
        );
        connection.release();
      });
    });
  },
  //获取分类
  getType(req, res, next) {
    let postData = req.query;
    pool.getConnection((err, connection) => {
      connection.query(sqlMap.type.getType, (err, result) => {
        if (err) {
          res.json({ code: 0, msg: "获取数据失败" });
          log.writeLog("<getType>" + err, "err");
        } else {
          res.json({ code: 1, data: result });
        }

        log.writeLog("sql:" + sqlMap.type.getType + ";params:" + ";", "sql");
        connection.release();
      });
    });
  },
  //获取评论
  getComment(req, res, next) {
    let postData = req.query;
    pool.getConnection((err, connection) => {
      connection.query(
        sqlMap.article.getComment,
        [postData.id],
        (err, result) => {
          if (err) {
            res.json({ code: 0, msg: "获取数据失败" });
            log.writeLog("<getComment>" + err, "err");
          } else {
            res.json({ code: 1, data: result });
          }
          log.writeLog(
            "sql:" + sqlMap.article.getComment + ";params:" + ";",
            "sql"
          );
          connection.release();
        }
      );
    });
  },
  //添加评论
  addComment(req, res, next) {
    const {
      avatar,
      content,
      blog_id,
      parent_comment_id,
      nickname,
      admin_comment,
      email,
    } = req.body;
    const postBody = {
      admin_comment: admin_comment,
      avatar: avatar,
      content: content,
      blog_id: blog_id,
      nickname: nickname,
      parent_comment_id: parent_comment_id,
      email: email,
      create_time: new Date(),
    };
    pool.getConnection((err, connection) => {
      connection.query(sqlMap.article.addComment, [postBody], (err, result) => {
        if (err) {
          res.json({ code: 0, msg: "获取数据失败" });
          log.writeLog("<addComment>" + err, "err");
        } else {
          res.json({ code: 1, data: result });
        }
        log.writeLog(
          "sql:" +
            sqlMap.article.addComment +
            ";params:" +
            JSON.stringify(postBody) +
            ";",
          "sql"
        );
        connection.release();
      });
    });
  },
  //获取归档列表
  getFilingList(req, res, next) {
    let postData = req.query;
    pool.getConnection((err, connection) => {
      connection.query(sqlMap.article.getFilingList, (err, result) => {
        if (err) {
          res.json({ code: 0, msg: "获取数据失败" });
          log.writeLog("<getFilingList>" + err, "err");
        } else {
          res.json({ code: 1, data: result });
        }

        log.writeLog(
          "sql:" + sqlMap.article.getFilingList + ";params:" + ";",
          "sql"
        );
        connection.release();
      });
    });
  },
  //编辑connect
  editBlogById(req, res, next) {
    const { type_name,id, html_content, content, description, title, type_id,high,low,mid,version,pdfurl } = req.body;
    const postBody = {
      html_content: html_content,
      content: content,
      description: description,
      title: title,
      type_id: parseInt(type_id),
      version:version,
      high:high,
      low:low,
      mid:mid,
      pdfurl:pdfurl,
      type_name:type_name
    };
    if (!postBody.type_id) delete postBody.type_id;
    pool.getConnection((err, connection) => {
      connection.query(
        sqlMap.article.editBlogById,
        [postBody, id],
        (err, result) => {
          if (err) {
            res.json({ code: 0, msg: "修改失败" });
            log.writeLog("<editBlogById>" + err, "err");
          } else {
            res.json({ code: 1, data: result });
          }

          log.writeLog(
            "sql:" +
              sqlMap.article.editBlogById +
              ";params:" +
              JSON.stringify(postBody) +
              "," +
              id +
              ";",
            "sql"
          );
          connection.release();
        }
      );
    });
  },
  //添加connect
  addBlog(req, res, next) {
    const { type_name,html_content, content, description, title, type_id ,high,low,mid,version,pdfurl} = req.body;
    console.log(req,"===")
    const postBody = {
      type_name:type_name,
      html_content: html_content,
      type_id: parseInt(type_id),
      content: content,
      description: description,
      title: title,
      views: 0,
      published: 1,
      is_top: "0",
      create_time: new Date(),
      version:version,
      high:high,
      low:low,
      mid:mid,
      pdfurl:pdfurl
    };
    if (!postBody.type_id) delete postBody.type_id;
    pool.getConnection((err, connection) => {
      connection.query(sqlMap.article.addBlog, [postBody], (err, result) => {
        console.log("article",postBody)
        if (err) {
          res.json({ code: 0, msg: "添加失败" });
          log.writeLog("<addBlog>" + err, "err");
        } else {
          res.json({ code: 1, data: result });
        }
        log.writeLog(
          "sql:" +
            sqlMap.article.addBlog +
            ";params:" +
            JSON.stringify(postBody) +
            ";",
          "sql"
        );
        connection.release();
      });
    });
  },
  //添加联系方式
  addTel(req, res, next){
    const { email, telegram, github} = req.body;
    
    const postBody = {
      email: email,
      telegram: telegram,
      github: github,
    };
    //if (!postBody.type_id) delete postBody.type_id;
    pool.getConnection((err, connection) => {
      connection.query(sqlMap.article.addTel, [postBody], (err, result) => {
        console.log("addTel",postBody)
        if (err) {
          res.json({ code: 0, msg: "添加失败" });
          log.writeLog("<addTel>" + err, "err");
        } else {
          res.json({ code: 1, data: result });
        }
        log.writeLog(
          "sql:" +
            sqlMap.article.addBlog +
            ";params:" +
            JSON.stringify(postBody) +
            ";",
          "sql"
        );
        connection.release();
      });
    });
  },
  deleteTag2Blog(req, res, next) {
    const postBody = req.body;
    pool.getConnection((err, connection) => {
      connection.query(
        sqlMap.article.deleteTag2Blog,
        [postBody.blogid, postBody.tagid],
        (err, result) => {
          if (err) {
            res.json({ code: 0, msg: "获取数据失败" });
            log.writeLog("<deleteTag2Blog>" + err, "err");
          } else {
            res.json({ code: 1, data: result });
          }
          log.writeLog(
            "sql:" +
              sqlMap.article.deleteTag2Blog +
              ";params:" +
              JSON.stringify(postBody) +
              ";",
            "sql"
          );
          connection.release();
        }
      );
    });
  },
  addTag2Blog(req, res, next) {
    const postBody = req.body;
    pool.getConnection((err, connection) => {
      connection.query(
        sqlMap.article.addTag2Blog,
        postBody.tagIdList,
        (err, result) => {
          if (err) {
            res.json({ code: 0, msg: "获取数据失败" });
            log.writeLog("<addTag2Blog>" + err, "err");
          } else {
            res.json({ code: 1, data: result });
          }
          log.writeLog(
            "sql:" +
              sqlMap.article.addTag2Blog +
              ";params:" +
              JSON.stringify(postBody.tagIdList) +
              ";",
            "sql"
          );
          connection.release();
        }
      );
    });
  },
  //浏览connect
  visitBlog(req, res, next) {
    const { id } = req.body;
    pool.getConnection((err, connection) => {
      connection.query(sqlMap.article.visitBlog, [id, id], (err, result) => {
        if (err) {
          res.json({ code: 0, msg: "获取数据失败" });
          log.writeLog("<visitBlog>" + err, "err");
        } else {
          res.json({ code: 1, data: result });
        }

        log.writeLog(
          "sql:" + sqlMap.article.visitBlog + ";params:" + id + ";",
          "sql"
        );
        connection.release();
      });
    });
  },
  //置顶connect
  toTopBlog(req, res, next) {
    const { id, isTop } = req.body;
    pool.getConnection((err, connection) => {
      connection.query(sqlMap.article.toTopBlog, [isTop, id], (err, result) => {
        if (err) {
          res.json({ code: 0, msg: "操作失败" });
          log.writeLog("<toTopBlog>" + err, "err");
        } else {
          res.json({ code: 1, data: result });
        }
        log.writeLog(
          "sql:" +
            sqlMap.article.toTopBlog +
            ";params:" +
            isTop +
            "," +
            id +
            ";",
          "sql"
        );
        connection.release();
      });
    });
  },
  //删除（隐藏）connect
  deleteBlog(req, res, next) {
    const { id } = req.body;
    pool.getConnection((err, connection) => {
      connection.query(sqlMap.article.deleteBlog, [id], (err, result) => {
        if (err) {
          res.json({ code: 0, msg: "操作失败" });
          log.writeLog("<deleteBlog>" + err, "err");
        } else {
          res.json({ code: 1, data: result });
        }
        log.writeLog(
          "sql:" + sqlMap.article.deleteBlog + ";params:" + id + ";",
          "sql"
        );
        connection.release();
      });
    });
  },
  //获取文章阅读量
  getArticleView(req, res, next) {
    pool.getConnection((err, connection) => {
      connection.query(sqlMap.statistics.getArticleView, (err, result) => {
        if (err) {
          res.json({ code: 0, msg: "操作失败" });
          log.writeLog("<getArticleView>" + err, "err");
        } else {
          res.json({ code: 1, data: result });
        }
        log.writeLog(
          "sql:" + sqlMap.statistics.getArticleView + ";params:;",
          "sql"
        );
        connection.release();
      });
    });
  },
  //获取分类阅读量
  getTypeView(req, res, next) {
    pool.getConnection((err, connection) => {
      connection.query(sqlMap.statistics.getTypeView, (err, result) => {
        if (err) {
          res.json({ code: 0, msg: "操作失败" });
          log.writeLog("<getTypeView>" + err, "err");
        } else {
          res.json({ code: 1, data: result });
        }
        log.writeLog(
          "sql:" + sqlMap.statistics.getTypeView + ";params:;",
          "sql"
        );
        connection.release();
      });
    });
  },
  //获取每日访问量
  getDateVisit(req, res, next) {
    pool.getConnection((err, connection) => {
      connection.query(sqlMap.statistics.getDateVisit, (err, result) => {
        if (err) {
          res.json({ code: 0, msg: "操作失败" });
          log.writeLog("<getDateVisit>" + err, "err");
        } else {
          res.json({ code: 1, data: result });
        }
        log.writeLog(
          "sql:" + sqlMap.statistics.getDateVisit + ";params:;",
          "sql"
        );
        connection.release();
      });
    });
  },
  //获取时间段访问量
  getHourVisit(req, res, next) {
    pool.getConnection((err, connection) => {
      connection.query(sqlMap.statistics.getHourVisit, (err, result) => {
        if (err) {
          res.json({ code: 0, msg: "操作失败" });
          log.writeLog("<getHourVisit>" + err, "err");
        } else {
          res.json({ code: 1, data: result });
        }
        log.writeLog(
          "sql:" + sqlMap.statistics.getHourVisit + ";params:;",
          "sql"
        );
        connection.release();
      });
    });
  },
  //获取城市访问量
  getCityVisit(req, res, next) {
    pool.getConnection((err, connection) => {
      connection.query(sqlMap.statistics.getCityVisit, (err, result) => {
        if (err) {
          res.json({ code: 0, msg: "操作失败" });
          log.writeLog("<getCityVisit>" + err, "err");
        } else {
          res.json({ code: 1, data: result });
        }
        log.writeLog(
          "sql:" + sqlMap.statistics.getCityVisit + ";params:;",
          "sql"
        );
        connection.release();
      });
    });
  },
  //获取城市时间访问量
  getDateCityVisit(req, res, next) {
    pool.getConnection((err, connection) => {
      connection.query(sqlMap.statistics.getDateCityVisit, (err, result) => {
        if (err) {
          res.json({ code: 0, msg: "操作失败" });
          log.writeLog("<getDateCityVisit>" + err, "err");
        } else {
          res.json({ code: 1, data: result });
        }
        log.writeLog(
          "sql:" + sqlMap.statistics.getDateCityVisit + ";params:;",
          "sql"
        );
        connection.release();
      });
    });
  },
  //未读评论
  getNeedReadComment(req, res, next) {
    pool.getConnection((err, connection) => {
      connection.query(sqlMap.article.getNeedReadComment, (err, result) => {
        if (err) {
          res.json({ code: 0, msg: "操作失败" });
          log.writeLog("<getNeedReadComment>" + err, "err");
        } else {
          res.json({ code: 1, data: result });
        }
        log.writeLog(
          "sql:" + sqlMap.article.getNeedReadComment + ";params:;",
          "sql"
        );
        connection.release();
      });
    });
  },
  //阅读评论
  readComment(req, res, next) {
    const { id } = req.body;
    pool.getConnection((err, connection) => {
      connection.query(sqlMap.article.readComment, [id], (err, result) => {
        if (err) {
          res.json({ code: 0, msg: "操作失败" });
          log.writeLog("<readComment>" + err, "err");
        } else {
          res.json({ code: 1, data: result });
        }
        log.writeLog(
          "sql:" + sqlMap.article.readComment + ";id:" + id + ";",
          "sql"
        );
        connection.release();
      });
    });
  },
  //全部已读
  readAllComment(req, res, next) {
    pool.getConnection((err, connection) => {
      connection.query(sqlMap.article.readAllComment, (err, result) => {
        if (err) {
          res.json({ code: 0, msg: "操作失败" });
          log.writeLog("<readAllComment>" + err, "err");
        } else {
          res.json({ code: 1, data: result });
        }
        log.writeLog(
          "sql:" + sqlMap.article.readAllComment + ";params:;",
          "sql"
        );
        connection.release();
      });
    });
  },
};
